<?php

namespace app\apiadmin\controller\aliyun;

use app\common\controller\BaseController;
use app\common\utils\Res;
use think\facade\Db;

/**
 * 语音通知
 * 2024年4月18日 20:46:22
 * @author Sani
 */
//header('Content-type:text/html;charset=utf-8');
class AliyunVmsController
{
    private $_accessKeyId = "LTAI5tEjCuzTNY5feKMXFrLv";   #标识用户
    private $_accessSecret = "TVzEn6y3K6AVQgoBDnzaejPk7Nw9yL";  #验证用户秘钥
    private $_voiceCode = "7c4671e9-fc24-459c-a131-3c61822838c6.wav";  #短信模板ID c27b4136-c2dd-4b98-9a1c-6af0504da9f4.wav
    
    public function __construct()
    {
        $this->_accessKeyId = env('ali.accessKeyId', 'LTAI5tEjCuzTNY5feKMXFrLv');
        $this->_accessSecret = env('ali.accessSecret', 'TVzEn6y3K6AVQgoBDnzaejPk7Nw9yL');
        $this->_voiceCode = env('ali.startLiveVoiceTel', '7c4671e9-fc24-459c-a131-3c61822838c6.wav');
    }

    /**
     * 发送短信
     * @param string $tel 电话
     * @param string $remark 备注
     * @return void
     * @author Sani
     * 2024年4月19日 01:44:36
     */
    public function sendVms($data, $liveId, $remark='siyu开播电话语音提醒')
    {
        $url = $this->_getUrl($data['tel']);
        $result = $this->_curlRuqust($url);
//        $result = ['Message'=>'ok','RequestId'=>"D36070AD-6C96-5781-9051-0EC89CFF1089",'CallId'=>'145441162649^132187947649','Code'=>'OK'];
//        var_dump($result);die;
        //成功
        // array (size=4)
        // 'Message' => string 'OK' (length=2)
        // 'RequestId' => string '1FC63302-5B6C-551B-9D8E-E51BFD04BC97' (length=36)
        // 'CallId' => string '141875462924^128625837925' (length=25)
        // 'Code' => string 'OK' (length=2)
        //失败
        // array (size=3)
        // 'Message' => string '该被叫号触发被叫流控,partnerId=100000082628820,prodId=11000000300006' (length=78)
        // 'RequestId' => string 'DB55C453-28D7-54C5-84EA-5405B930C9E6' (length=36)
        // 'Code' => string 'isv.BUSINESS_LIMIT_CONTROL' (length=26)
        $log['qiyeid'] = 1;
        $log['source'] = 'live';
        $log['phone'] = $data['tel'];
        $log['status'] = 0;
        $log['biz_id'] = '';
        $log['remark'] = $remark;
        $log['type'] = 4;
        $log['message'] = $result['Code'].'#'.$result['Message'];
        $log['time'] = date('Y-m-d H:i:s', time());
        if ($result['Code'] == 'OK') {
            $log['status'] = 1;
            $log['biz_id'] = $result['CallId'];
            $order_update['voice_tel'] = 1;
        }
        DB::table('xh_open_platform_sms_voice_execute')->insert($log);
        DB::table('xh_siyu_invitation_user')->where(['wx_unionid'=>$data['wx_union_id'],'liveId'=>$liveId])->save($order_update);
        
    }

    private function _getUrl($CalledNumber)
    {
        $Timestamp = gmdate("Y-m-d\TH:i:s\Z");

        #系统参数
        $commonParams = [
            'Action' => 'SingleCallByVoice',
            'Version' => '2017-05-25',
            'Format' => 'json',
            'AccessKeyId' => $this->_accessKeyId,
            'SignatureNonce' => $this->_getUuid(),
            'Timestamp' => $Timestamp,
            'SignatureMethod' => 'HMAC-SHA1',
            'SignatureVersion' => "1.0",
        ];

        #业务API参数
        $normalParams = array('CalledNumber' => $CalledNumber, 'VoiceCode' => $this->_voiceCode);

        #合并参数
        $datas = array_merge($commonParams, $normalParams);

        #升序排列
        ksort($datas);

        #拼接加密字符串
        $sortedQueryStringTmp  = "";
        foreach ($datas as $key => $val) {
            $sortedQueryStringTmp  .= "&" . $key . "=" . $this->_encode($val);
        }
        $stringToSign = "GET&%2F&" . $this->_encode(substr($sortedQueryStringTmp, 1));

        #加密转码 
        $sign = base64_encode(hash_hmac("sha1", $stringToSign, $this->_accessSecret . "&", true));

        #生成签名
        $signature = $this->_encode($sign);

        #拼接请求链接
        $api = 'dyvmsapi.aliyuncs.com';
        $url = "https://" . $api . "/?Signature=" . $signature . $sortedQueryStringTmp;

        return $url;
    }

    /**
     * PHP生成 UUID
     * @return [type] [description]
     */
    private static function _getUuid()
    {
        $chars = md5(uniqid(mt_rand(), true));
        $uuid = substr($chars, 0, 8) . '-'
            . substr($chars, 8, 4) . '-'
            . substr($chars, 12, 4) . '-'
            . substr($chars, 16, 4) . '-'
            . substr($chars, 20, 12);
        return $uuid;
    }

    /**
     * 对应CURL请求
     * @param  [type] $url [description]
     * @return [type]      [description]
     */
    private function _curlRuqust($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            "x-sdk-client" => "php/2.0.0"
        ));
        if (substr($url, 0, 5) == 'https') {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        $rtn = curl_exec($ch);
        if ($rtn === false) {
            trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
        }
        curl_close($ch);
        $rtn = json_decode($rtn, true);
        return $rtn;
    }

    /**
     * 阿里云短信对应转码替换
     * @param  [type] $str [description]
     * @return [type]      [description]
     */
    private function _encode($string)
    {
        $res = urlencode($string);
        $res = preg_replace("/\+/", "%20", $res);
        $res = preg_replace("/\*/", "%2A", $res);
        $res = preg_replace("/%7E/", "~", $res);
        return $res;
    }
}
